import { BrowserWindow, app, ipcMain } from 'electron';
import * as path from 'node:path';
import WinState from "electron-win-state";
import { dname } from '../main';
import { pathToFileURL } from 'node:url';
import Store from 'electron-store'; // 导入electron-store用于保存窗口大小

export let mainWindow: BrowserWindow | null = null;
export let newWin: BrowserWindow | null = null;

// 存储窗口和插件任务的映射关系
const windowPluginMap = new Map<number, string>();

// 初始化electron-store
const windowStateStore = new Store({
    name: 'window-state',
    defaults: {
        mainWindow: { width: 1366, height: 768 },
        pluginWindows: {}
    }
});

// 保存窗口大小和位置
function saveWindowState(windowId: number, windowName: string, window: BrowserWindow) {
    if (!window) return;
    
    const bounds = window.getBounds();
    
    if (windowName === 'main') {
        windowStateStore.set('mainWindow', bounds);
    } else {
        const pluginWindows = windowStateStore.get('pluginWindows') as Record<string, any>;
        pluginWindows[windowName] = bounds;
        windowStateStore.set('pluginWindows', pluginWindows);
    }
    // console.log(`保存窗口 ${windowName} 的大小和位置:`, bounds);
}

// 获取保存的窗口大小和位置
function getWindowState(windowName: string) {
    if (windowName === 'main') {
        return windowStateStore.get('mainWindow') as { width: number, height: number, x?: number, y?: number };
    } else {
        const pluginWindows = windowStateStore.get('pluginWindows') as Record<string, any>;
        return pluginWindows[windowName] || { width: 1200, height: 800 };
    }
}

export function createNewWindow(value: string, htmlPath: string) {
    console.log('创建窗口:', htmlPath);
    if (!htmlPath || typeof htmlPath !== 'string') {
        throw new Error(`Invalid htmlPath: ${htmlPath}`);
    }

    // 获取保存的窗口状态
    const savedState = getWindowState(value);
    
    const winState = new WinState({});
    newWin = new BrowserWindow({
            ...winState.winOptions,
            width: savedState.width || 1200,
            height: savedState.height || 800,
            x: savedState.x,
            y: savedState.y,
            frame: false,
            autoHideMenuBar: true, 
            title: `${value}`,
            icon: process.env.NODE_ENV === 'development'
                ? 'public/rb.ico'
                : path.join(process.resourcesPath, 'public/rb.ico'), //生产环境路径
            webPreferences: {
                // 禁用不需要的实验性功能
                experimentalFeatures: false,
                contextIsolation: true,
                nodeIntegration: false,
                webSecurity: false,
                sandbox: true,
                spellcheck: false,
                disableBlinkFeatures: 'AutomationControlled',
                preload: path.join(dname, 'preload.js'),
                devTools: true,
            },
    });
    
    // 存储窗口ID和插件名称的映射关系
    if (newWin) {
        windowPluginMap.set(newWin.id, value);
    }
    
    newWin.on('ready-to-show', () => {
        newWin?.setTitle(`${value}`);
        newWin?.center();
        newWin?.show();
    });

    // 监听窗口大小变化事件
    newWin.on('resize', () => {
        if (newWin) {
            const pluginName = windowPluginMap.get(newWin.id);
            if (pluginName) {
                saveWindowState(newWin.id, pluginName, newWin);
            }
        }
    });
    
    // 监听窗口移动事件
    newWin.on('move', () => {
        if (newWin) {
            const pluginName = windowPluginMap.get(newWin.id);
            if (pluginName) {
                saveWindowState(newWin.id, pluginName, newWin);
            }
        }
    });
    
    newWin.on('close', () => {
        if (newWin) {
            // 获取关闭窗口对应的插件名称
            const pluginName = windowPluginMap.get(newWin.id);
            if (pluginName) {
                // 保存窗口大小和位置
                saveWindowState(newWin.id, pluginName, newWin);
            }
        }
    });
    
    newWin.on('closed', () => {
        if (newWin) {
            // 获取关闭窗口对应的插件名称
            const pluginName = windowPluginMap.get(newWin.id);
            if (pluginName) {
                // 终止该插件的所有运行任务
                terminatePluginTasks(pluginName);
                // 从映射中删除
                windowPluginMap.delete(newWin.id);
            }
            newWin = null;
        }
    });

    try {
        if (htmlPath.startsWith('file://')) {
            newWin.loadURL(htmlPath);
        } else {
            newWin.loadFile(htmlPath);
        }
    } catch (error) {
        console.error('加载窗口失败:', error);
        throw error;
    }
}

// 终止指定插件的所有运行任务
function terminatePluginTasks(pluginName: string) {
    console.log(`终止插件 ${pluginName} 的所有任务`);
    
    // 获取主进程中存储的所有运行中的任务
    const runningTasks = getRunningPluginTasks();
    
    if (!runningTasks || runningTasks.size === 0) {
        console.log('没有正在运行的任务');
        return;
    }
    
    // 遍历所有任务，终止属于该插件的任务
    for (const [taskId, task] of runningTasks.entries()) {
        if (task.pluginName === pluginName) {
            console.log(`终止任务: ${taskId}`);
            try {
                // 中断任务
                task.controller.abort();
                console.log(`已中断任务: ${taskId}`);
            } catch (error) {
                console.error(`终止任务 ${taskId} 失败:`, error);
            }
        }
    }
}

// 从主进程获取正在运行的任务列表
function getRunningPluginTasks() {
    // 使用全局对象中的runningPluginTasks
    // 这是在main.ts中设置的
    return (global as any).runningPluginTasks || new Map();
}

export function createWindow() {
    // 获取保存的主窗口状态
    const savedState = getWindowState('main');
    
    const winState = new WinState({});
    mainWindow = new BrowserWindow({
        ...winState.winOptions,
        frame: false, // 隐藏窗口边框和标题栏
        autoHideMenuBar: true, // 隐藏菜单栏
        width: savedState.width || 1366,
        height: savedState.height || 768,
        x: savedState.x,
        y: savedState.y,
        title: 'Automation Tools Platform',
        icon: process.env.NODE_ENV === 'development'
            ? 'public/rb.ico'
            : '../../public/rb.ico',
        webPreferences: {
            // 禁用不需要的实验性功能
            experimentalFeatures: false,

            contextIsolation: true,
            nodeIntegration: false,
            webSecurity: false,
            sandbox: true,  // 添加sandbox

            spellcheck: false,
            disableBlinkFeatures: 'AutomationControlled',
            
            preload: path.join(dname, 'preload.js'),
            devTools: true,
        },
    });
    winState.manage(mainWindow);
    
    // 监听窗口大小变化事件
    mainWindow.on('resize', () => {
        if (mainWindow) {
            saveWindowState(mainWindow.id, 'main', mainWindow);
        }
    });
    
    // 监听窗口移动事件
    mainWindow.on('move', () => {
        if (mainWindow) {
            saveWindowState(mainWindow.id, 'main', mainWindow);
        }
    });
    
    // 窗口关闭前保存状态
    mainWindow.on('close', () => {
        if (mainWindow) {
            saveWindowState(mainWindow.id, 'main', mainWindow);
        }
    });

    mainWindow.on('ready-to-show', () => {
        if (mainWindow) {
            mainWindow.setTitle(`Automation Tools Platform v${app.getVersion()}`);
            mainWindow.center();
            mainWindow.show();
        }
    });

    mainWindow.on('closed', () => {
        mainWindow = null;
    });
    // 修改加载路径处理逻辑
    const loadUrl = process.env.VITE_DEV_SERVER_URL || 
    pathToFileURL(
      path.join(
        app.isPackaged 
          ? path.join(dname, '../../app/web-dist')  // 修正打包后路径层级
          : path.join(dname, '../app/web-dist'), 
        'index.html'
      )
    ).href;

    mainWindow.loadURL(loadUrl).then(() => {
        // win?.webContents.openDevTools({ mode: 'undocked' });
    }).catch(error => {
        console.error('加载失败:', error);
        console.log('最终加载路径:', loadUrl); // 添加路径日志
    });
}